const BaseController = require("./base/base");
const Result = require("../utils/result");
const BranchModel = require("../model/branch");
const { getTokenUser, isAdmin } = require("../middlewares/auth");
class BranchController extends BaseController {
  constructor() {
    super();
  }

  findBranchByPage(req, res, next) {
    setTimeout(async () => {
      try {
        let { branch = '' } = req.query;
        let _filter = {}
        if (branch) _filter = { branch: { $regex: branch, $options: '$i' } }

        let { page = 1, pagesize = 1 } = req.query
        page *= 1;
        pagesize *= 1;
        let total = await BranchModel.countDocuments(_filter)
        let list = await BranchModel.find(_filter, { password: 0 }).skip((page - 1) * pagesize).limit(pagesize).sort({ '_id': -1 }).exec()
        res.json(Result.ok("success", { total, list }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  findAll(req, res, next) {
    setTimeout(async () => {
      try {
        let list = await BranchModel.find({})
        res.json(Result.ok("success", { total:list.length, list }));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  addBranch(req, res, next) {
    setTimeout(async () => {
      try {
        let user = await new BranchModel({ ...req.body }).save();
        res.json(!user ? Result.fail("添加失败") : Result.ok("添加成功"));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  findOneById(req, res, next) {
    setTimeout(async () => {
      try {
        let { id } = req.params;
        let user = await BranchModel.findById({ _id: id })
        res.json(!user ? Result.fail("fail") : Result.ok("success", user));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  updateOneById(req, res, next) {
    setTimeout(async () => {
      try {
        //{"acknowledged":true,"matchedCount":1,"upsertedId":null,"upsertedCount":0,"matchedCount":1}
        let ret = await BranchModel.updateOne({ _id: req.params.id }, req.body)
        res.json(!ret.matchedCount ? Result.fail("修改失败") : Result.ok("修改成功"));
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
  deleteOneById(req, res, next) {
    setTimeout(async () => {
      try {
        //{ deletedCount: 1 }
        let ret = await BranchModel.deleteOne({ _id: req.params.id })
        res.json(!ret.deletedCount ? Result.fail("删除失败") : Result.ok("删除成功"))
      } catch (err) {
        res.json(Result.error(err));
      }
    })
  }
}
module.exports = new BranchController().resolve();